<template>
  <div>
    <cfg-table
      ref="table"
      :columns="columns"
      :data="data"
      :loading="loading"
      :config="config"
      :pageSizeOpts="pageSizeOpts"
      :pageNavigation="pageNavigation"
      :queryFormItem="queryFormItem"
      :collapseFormItem="collapseFormItem"
      :additionalAction="additionalAction"
      @loadPage="loadPage"
      @handleCreate="handleCreate"
      @handleDetail="handleDetail"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @handleDeleteMultiple="handleDeleteMultiple"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    ></cfg-table>
    <new-add-modal
      v-bind="addNewPanel"
      :modelType="modelType"
      :columns="addFormColumns"
      :rules="rules"
      @submit="handleNewAddSubmit"
    ></new-add-modal>
    <edit-modal
      v-bind="editPanel"
      :modelType="modelType"
      :columns="formColumns"
      :rules="rules"
      @submit="handleEditSubmit"
    ></edit-modal>
    <read-modal
      v-bind="readPanel"
      :modelType="modelType"
      :columns="columns"
      :rules="rules"
    ></read-modal>
    <Modal
      v-model="showPrice"
      title="单价记录"
      :footer-hide="true"
      width="1200"
    >
      <energyUnitPrice
        v-if="showPrice"
        :energyCode="Ecode"
        :energyName="Ename"
      />
    </Modal>
    <Modal
      v-model="showCoal"
      title="标准煤系数记录"
      :footer-hide="true"
      width="1200"
    >
      <energyStandardCoal
        v-if="showCoal"
        :energyCode="Ecode"
        :energyName="Ename"
      />
    </Modal>
  </div>
</template>

<script>
import newAddModal from "@/pages/components/newAddModal.vue";
import editModal from "@/pages/components/editModal.vue";
import readModal from "@/pages/components/readModal.vue";
import energyStandardCoal from "./components/energyStandardCoal.vue";
import energyUnitPrice from "./components/energyUnitPrice.vue";
import { typeClassName } from "@/pages/config/classNameMap";
import mixin from "@/pages/components/mixins/mixin";
import columnsMixin from "./config";
export default {
  components: {
    newAddModal,
    editModal,
    readModal,
    energyStandardCoal,
    energyUnitPrice,
  },
  name: "energyInfo",
  mixins: [mixin, columnsMixin],
  data() {
    return {
      classObject: null, // 单个实例
      collectionObject: null, // 所有实例
      energyStatus: [], // 能源状态
      energyStatusClassObject: null, // 状态模型
      typeOptions: [], // 能源类型下拉框
      typeClassObject: null, // 能源类型实例
      className: typeClassName["energyInfo"].className,
      type: typeClassName["energyInfo"].type,
      modelType: typeClassName["energyInfo"].modelType,
      addNewPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 2,
      },
      editPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 2,
        data: {},
      },
      readPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 2,
        data: {},
      },
      rules: {
        sf_energyCode: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        sf_energyName: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        energySimpleCode: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        energySource: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "不能为空", trigger: "blur" }],
        typeName: [{ required: true, message: "不能为空", trigger: "blur" }],
        measuringUnit: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        point: [{ required: true, message: "不能为空", trigger: "blur" }],
        standardCoal: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
            type: "number",
          },
        ],
        weight: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
            type: "number",
          },
        ],
        target: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
            type: "number",
          },
        ],
        unitPrice: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
            type: "number",
          },
        ],
      },
      loading: false,
      config: {
        search: true,
        addButton: true,
        batchDeleteButton: true,
        tableSizeIcon: true,
        fullscreenIcon: true,
        refreshIcon: false,
        columnSettingIcon: true,
        action: true,
        additionalAction: true,
      },
      pageSizeOpts: [10, 30, 50, 100],
      pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 },
      sourceOptions: [
        { label: "外采", value: "out" },
        { label: "自产", value: "product" },
      ],
      showPrice: false,
      showCoal: false,
      Ecode: "",
      Ename: "",
      priceClassObject: null,
      coalClassObject: null,
      changeParams: {
        standardCoal: 0, // 标准煤系数
        unitPrice: 0, // 单价
      },
    };
  },
  computed: {
    additionalAction() {
      let additionalAction = {
        key: "additionalAction",
        title: {
          "zh-CN": "附加操作",
          "en-US": "additional action",
        }[this.G_Locale],
        slot: "additionalAction",
        width: 250,
        fixed: "right",
        align: "center",
        show: true,
        buttons: [
          {
            title: {
              "zh-CN": "单价记录",
              "en-US": "read price",
            }[this.G_Locale],
            key: "readPrice",
            event: (row, index) => this.readPrice(row, index),
          },
          {
            title: {
              "zh-CN": "标准煤记录",
              "en-US": "read coefficient",
            }[this.G_Locale],
            key: "readCoefficient",
            event: (row, index) => this.readCoefficient(row, index),
          },
        ],
      };
      this.G_IsMobile && (additionalAction.width = 90);
      return additionalAction;
    },
    data() {
      if (!!this.collectionObject) {
        return this.collectionObject.records.map((d) => {
          return {
            ...d,
            ...d.values,
          };
        });
      } else {
        return [];
      }
    },
  },
  beforeMount() {
    this.collectionObject = this.$modelObject.create(
      `${this.modelType}Collection`
    );
    this.classObject = this.$modelObject.create(this.modelType);
    this.priceClassObject = this.$modelObject.create(
      typeClassName["energyUnitPrice"].modelType
    ); // 单价表
    this.coalClassObject = this.$modelObject.create(
      typeClassName["energyStandardCoal"].modelType
    ); // 标准煤表
    this.energyStatusClassObject = this.$modelObject.create(
      typeClassName["paramStatus"].modelType
    );
    this.typeClassObject = this.$modelObject.create(
      `${typeClassName["energyType"].modelType}`
    );
    this.setOptions(
      "paramStatus",
      this.energyStatusClassObject,
      "energyStatus"
    );
    this.setOptionsByHier("energyType", this.typeClassObject, "typeOptions", {
      label: "sf_name",
      value: "sf_code",
    });
    this.loadPage(this.pageNavigation, null);
  },
  mounted() {},
  methods: {
    /**
     * 删除条件
     * 能源基础档案管理，不能删除或停用被仪表关联的能源
     */
    deleteCondition(ids) {
      let flag = true;
      this.collectionObject.records
        .filter((d) => ids.includes(d.id))
        .map((item) => {
          if (
            item.others &&
            item.others.basic &&
            item.others.basic.length > 0
          ) {
            flag = false;
          }
        });
      if (!flag) {
        this.$Message.error("不能删除被仪表关联的能源");
      }
      return flag;
    },
    /**
     * 编辑条件
     * 能源基础档案管理，不能停用被仪表关联的能源
     */
    editCondition(data) {
      let flag = true;
      if (
        data.others &&
        data.others.basic &&
        data.others.basic.length > 0 &&
        data.values["status"] === "停用"
      ) {
        flag = false;
        this.$Message.error("不能停用被仪表关联的能源");
      }
      return flag;
    },
    /**
     * 新增确认时条件
     * 能源基础档案管理,新增时生成编码流水号
     */
    async addCondition(data) {
      let flag = true;
      let no = await this.$api.Common.getNextVal("eninfo");
      data.values["sf_energyCode"] = no;
      return flag;
    },
    // 查看单价记录
    readPrice(row, index) {
      this.showPrice = true;
      this.Ecode = row.values.sf_energyCode;
      this.Ename = row.values.sf_energyName;
    },
    // 查看标准煤记录
    readCoefficient(row, index) {
      this.showCoal = true;
      this.Ecode = row.values.sf_energyCode;
      this.Ename = row.values.sf_energyName;
    },
    // 在编辑的时候去判断单价和标准煤的变化
    async handleEdit(row, index) {
      // 先把旧值存下来，方便后续比对
      this.changeParams.standardCoal = row.values.standardCoal;
      this.changeParams.unitPrice = row.values.unitPrice;
      this.loading = true;
      if (
        await this.getRecord({
          type: row.type,
          className: row.className,
          id: row.id,
        })
      ) {
        //是否有编辑弹框打开条件且满足
        if (
          typeof this.editPanelOpenCondition === "function" &&
          !this.editPanelOpenCondition(this.classObject.record)
        ) {
          this.loading = false;
          return;
        }
        this.$set(this.editPanel, "data", this.classObject.record);
        this.$set(this.editPanel.drawer, "show", true);
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    //   handleNewAddSubmit(data) {
        
    // },
    // 提交的时候要去判断一下标准煤和单价
    async handleEditSubmit(data) {
      if (this.isNeedAddPriceRecord(data)) {
        this.addRecord(data, "energyUnitPrice");
      }
      if (this.isNeedAddCoalRecord(data)) {
        this.addRecord(data, "energyStandardCoal");
      }
      this.loading = true;
      //是否有编辑条件且满足
      if (
        typeof this.editCondition === "function" &&
        !(await this.editCondition(data))
      ) {
        this.loading = false;
        return;
      }
      this.classObject.setRecord(data);
      return this.classObject.update().then((flag) => {
        if (flag) {
          let index = this.collectionObject.records.findIndex(
            (item) => item.id === this.classObject.record.id
          );
          if (index !== -1) {
            this.collectionObject.records.splice(
              index,
              1,
              this.classObject.record
            );
          }
          this.loading = false;
          this.$set(this.editPanel.drawer, "show", false);
        } else {
          this.loading = false;
        }
      });
    },
    isNeedAddPriceRecord(data) {
      if (
        data.values.unitPrice &&
        data.values.unitPrice !== this.changeParams.unitPrice
      ) {
        return true;
      }
      return false;
    },
    isNeedAddCoalRecord(data) {
      if (
        data.values.standardCoal &&
        data.values.standardCoal !== this.changeParams.standardCoal
      ) {
        return true;
      }
      return false;
    },
    // 分别向已经变化的标准煤和单价表中添加数据
    addRecord(data, className) {
      let dataValues = {};
      dataValues.className = typeClassName[className].className;
      dataValues.type = typeClassName[className].type;
      dataValues.name = +new Date();
      dataValues.values = {
        sf_energyCode: data.values.sf_energyCode,
        sf_energyName: data.values.sf_energyName,
        simpleCode: data.values.energySimpleCode,
        source: data.values.energySource,
        type: data.values.typeName,
        measuringUnit: data.values.measuringUnit,
        point: data.values.point,
        coefficient: data.values.standardCoal,
        price: data.values.unitPrice,
      };
      this.loading = true;
      if (className === "energyUnitPrice") {
        this.priceClassObject.add(dataValues).then((flag) => {
          if (flag) {
            this.loading = false;
          } else {
            this.loading = false;
          }
        });
      } else {
        this.coalClassObject.add(dataValues).then((flag) => {
          if (flag) {
            this.loading = false;
          } else {
            this.loading = false;
          }
        });
      }
    },
  },
};
</script>
<style scoped lang="scss"></style>
